package edu.demo.recommend.exception;

import edu.demo.recommend.common.R;
import edu.demo.recommend.common.ResultCodeEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局的异常处理
 * @author hb
 */
@ControllerAdvice   //全局的异常切面类
public class GlobalExceptionHandler {
   //通用异常的处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();//可以将异常写入日志
        return R.error();
    }

    //通用异常的处理
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e){
        e.printStackTrace();//可以将异常写入日志
        return R.error().message(e.getMessage());
    }

    //自定义的异常
    @ExceptionHandler(RecommendBusinessException.class)
    @ResponseBody
    public R error(RecommendBusinessException e){
        e.printStackTrace();//可以将异常写入日志
        return R.error().message(e.getMessage());
    }

    //自定义的异常
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public R error(NoHandlerFoundException e){
        e.printStackTrace();//可以将异常写入日志
        return R.setResult(ResultCodeEnum.NO_HANDLER_FOUND);
    }
}
